package org.lzy.shop.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import org.lzy.shop.databinding.ItemBannerBinding
import org.lzy.shop.response.HomeResponse

/**
 * Banner轮播图适配器
 */
class BannerViewPagerAdapter : RecyclerView.Adapter<BannerViewPagerAdapter.BannerViewHolder>() {
    private var bannerList: List<HomeResponse.BannerDTO> = emptyList()
    private var onItemClickListener: ((position: Int) -> Unit)? = null

    /**
     * 更新轮播图数据
     */
    fun submitList(list: List<HomeResponse.BannerDTO>) {
        bannerList = list
        notifyDataSetChanged()
    }

    /**
     * 设置点击事件监听器
     */
    fun setOnItemClickListener(listener: (position: Int) -> Unit) {
        onItemClickListener = listener
    }

    /**
     * 获取指定位置的Banner数据
     */
    fun getData(position: Int): HomeResponse.BannerDTO? {
        return if (position in 0 until bannerList.size) bannerList[position] else null
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BannerViewHolder {
        val binding =
            ItemBannerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BannerViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BannerViewHolder, position: Int) {
        // 计算实际位置（用于无限滚动）
        val actualPosition = if (bannerList.isEmpty()) 0 else position % bannerList.size
        val bannerItem = bannerList[actualPosition]

        // 设置点击事件
        holder.binding.root.setOnClickListener {
            onItemClickListener?.invoke(actualPosition)
        }
    }

    override fun getItemCount(): Int {
        // 为了支持无限滚动，返回一个很大的值
        return if (bannerList.size > 1) Int.MAX_VALUE else bannerList.size
    }

    /**
     * Banner ViewHolder
     */
    inner class BannerViewHolder(val binding: ItemBannerBinding) :
        RecyclerView.ViewHolder(binding.root)
}